package com.riteny.oauth.core.tokenstore;

import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;

import java.util.Map;

/**
 * @author Riteny
 * 2021/5/7  17:04
 */
public class CustomAccessTokenConverter extends DefaultAccessTokenConverter {

    private CustomTokenStore customTokenStore;

    public CustomAccessTokenConverter(CustomTokenStore customTokenStore) {
        this.customTokenStore = customTokenStore;
    }

    /**
     * 將額外信息（用戶信息）添加到token中
     *
     * @return
     */
    @Override
    public Map<String, ?> convertAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {

        DefaultOAuth2AccessToken defaultOAuth2AccessToken = new DefaultOAuth2AccessToken(token);

        defaultOAuth2AccessToken.setAdditionalInformation(customTokenStore.readUserInfo(token, authentication));

        Map<String, ?> response = super.convertAccessToken(defaultOAuth2AccessToken, authentication);

        return response;
    }
}
